package moonlit.chill.pay.service.impl.ali;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import lombok.extern.slf4j.Slf4j;
import moonlit.chill.pay.cache.PayConfigDataCache;
import moonlit.chill.pay.constants.Constants;
import moonlit.chill.pay.exception.PayException;
import moonlit.chill.pay.service.PayStrategy;
import moonlit.chill.pay.util.AliPayClientUtil;
import moonlit.chill.pay.vo.PayConfig;
import moonlit.chill.pay.vo.TradeParam;
import moonlit.chill.pay.vo.PayResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author MoonlitChill
 * @date 2024/4/15 16:35
 */
@Slf4j
@Service("aliMiniPayStrategy")
public class AliMiniPayStrategyServiceImpl implements PayStrategy {
    @Resource
    private PayConfigDataCache payConfigDataCache;

    @Autowired
    private AliPayClientUtil aliPayClientUtil;

    @Override
    public PayResult<?> payMethod(TradeParam tradeParam) {
        log.info(String.format("支付宝小程序支付参数:%s", JSONUtil.toJsonStr(tradeParam)));
        PayResult<String> result = new PayResult<>();
        try {
            if (StrUtil.isEmpty(tradeParam.getMiniOpenId())){
                throw new PayException("用户ID不能为空");
            }
            PayConfig payConfig = payConfigDataCache.getPayConfig();
            AlipayClient alipayClient = aliPayClientUtil.getAliPayClient(payConfig);
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
            request.setNotifyUrl(payConfig.getNotifyUrl());
            JSONObject bizContent = new JSONObject();
            String outTradeNo = tradeParam.getTransNum();
            result.setTransNum(outTradeNo);
            bizContent.put("out_trade_no", outTradeNo);
            bizContent.put("total_amount", tradeParam.getTotalFee());
            bizContent.put("subject", tradeParam.getPayTitle());
            bizContent.put("product_code", "JSAPI_PAY");
            bizContent.put("buyer_id", tradeParam.getMiniOpenId());
            //bizContent.put("buyer_open_id", payParam.getMiniOpenId());
            bizContent.put("op_app_id", payConfig.getMiniAppId());
            bizContent.put("body", JSONUtil.toJsonStr(tradeParam.getAdditionalInfo()));
            bizContent.put("time_expire", DateUtil.format(tradeParam.getPayDeadLine(), DatePattern.NORM_DATETIME_PATTERN));
            request.setBizContent(JSONUtil.toJsonStr(bizContent));
            if (StrUtil.isNotEmpty(payConfig.getAppAuthToken())){
                request.putOtherTextParam("app_auth_token", payConfig.getAppAuthToken());
            }
            AlipayTradeCreateResponse response;
            if (payConfig.getAliType() == 0){
                //证书模式
                response = alipayClient.certificateExecute(request);
            } else {
                //密钥模式
                response = alipayClient.execute(request);
            }
            if (response.isSuccess()){
                JSONObject res = new JSONObject();
                res.put("tradeNO", response.getTradeNo());
                res.put("outTradeNo", response.getOutTradeNo());
                result.setSuccess(Boolean.TRUE);
                result.setResult(JSONUtil.toJsonStr(res));
            } else {
                result.error(response.getSubMsg(), Constants.PAY_FAIL_CODE);
            }
        } catch (Exception e) {
            result.errorWithException("支付失败，请重试", Constants.PAY_ERROR_CODE, e);
        }
        return result;
    }
}
